<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\Anchor;
use App\Models\BaseModel;
use App\Models\Scene;

class SceneService extends BaseService
{
    /**
     * 风景列表
     * @param $page
     * @param $pageSize
     * @param $keyword
     * @return array
     */
    public function list($page, $pageSize, $keyword = '', $anchorId = 0)
    {
        // 设置对象
        $model = Scene::query();
        // 关键词
        if ($keyword) {
            $model = $model->where('scene_name', 'like', '%' . $keyword . '%');
        }
        // 锚点
        if ($anchorId) {
            $model = $model->whereRaw('FIND_IN_SET(?, anchor_ids)', [$anchorId]);
        }
        // 状态
        $model = $model->where('status', BaseModel::STATUS_ENABLE);
        // 获取列表
        $result = $model
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['id', 'scene_name', 'scene_img', 'anchor_ids'], 'page', $page);

        $anchorNames = Anchor::query()->pluck('anchor_name', 'id') ?? [];
        $result->getCollection()->transform(function ($item) use ($anchorNames) {
            $item = json_decode($item, true);
            $item['scene_img'] = storageFirst($item['scene_img']);
            $anchorIds = explode(',', $item['anchor_ids']);
            $item['anchor_name'] = $anchorNames[$anchorIds[0]] ?? '';
            return $item;
        });

        return $this->successPage($result);
    }

    /**
     * 风景详情
     * @param $sceneId
     * @return array
     * @throws BusinessException
     */
    public function detail($sceneId)
    {
        // 获取数据
        $data = Scene::query()->where('id', $sceneId)->first();
        if (!$data) {
            $this->throwBusinessException('风景不存在');
        }
        $data->increment('views');
        $data = $data->toArray();

        $data['scene_img'] = storageMulti($data['scene_img']);
        // 锚点
        $anchorNames = Anchor::query()->pluck('anchor_name', 'id') ?? [];
        $anchorIds = explode(',', $data['anchor_ids']);
        $data['anchor_name'] = [];
        foreach ($anchorIds as $anchorId) {
            if ($anchorNames[$anchorId] ?? false) {
                $data['anchor_name'][] = [$anchorId => $anchorNames[$anchorId]];
            }
        }
        return $data;
    }
}
